<template>
  <el-dialog :visible="visible" width="40%" @close="visible = !visible">
    <title-line title="分配权限" />
    <el-tree
      :data="permissionList"
      show-checkbox
      default-expand-all
      node-key="id"
      ref="tree"
      highlight-current
      :props="defaultProps"
      @check="handleSelectChange"
    >
    </el-tree>
    <div slot="footer">
      <el-button @click="resetForm"> 取消 </el-button>
      <el-button type="primary" @click="handelConfirm"> 确定 </el-button>
    </div>
  </el-dialog>
</template>
<script>
export default {
  name: 'RoleTree',
  props: {
    roleId: {
      type: String | Number,
      default: ''
    },
    dialogVisible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      defaultProps: {
        value: 'id',
        label: 'title',
        children: 'children',
        disabled: val => {
          if (val.path === 'Home') {
            return true
          }
        }
      },
      permissionList: [],
      selectList: []
    }
  },
  computed: {
    visible: {
      get() {
        return this.dialogVisible
      },
      set(val) {
        this.$emit('update:dialogVisible', val)
      }
    }
  },
  created() {
    this.getNavs()
    this.getRoleNav()
  },
  mounted() {},
  methods: {
    // 监听选中树结构数据
    handleSelectChange(item, check) {
      this.selectList = check.checkedKeys
    },
    // 查询菜单权限
    async getNavs() {
      const { data } = await this.$http.system.menu.getNavs(this.roleId)
      this.permissionList = data
    },
    // 查询拥有的权限
    async getRoleNav() {
      const { data } = await this.$http.system.role.getRoleNav(this.roleId)
      this.selectList = [...data, 1]
      this.$refs.tree.setCheckedKeys([...data, 1])
    },
    // 修改角色权限
    async handelConfirm() {
      const params = {
        roleId: this.roleId,
        navigationIds: this.selectList
      }
      const { status, msg } = await this.$http.system.role.modifyRole(params)
      if (status === 200) {
        this.$message.success('分配成功')
        this.visible = false
        this.$emit('getList')
      } else {
        this.$message.error(msg)
      }
    },
    resetForm() {
      this.visible = false
    }
  }
}
</script>
<style></style>
